package com.example.demo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.rmi.ConnectIOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

@WebServlet("/DatabaseAccess")
public class DatabaseAccess extends HttpServlet {
    private static final long serialVersionUID = 1l;
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/user?useSSL=false";

    static final String USER = "root";
    static final String PASS = "123456";


    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection connection = null;
        Statement stmt = null;


        resp.setContentType("text/html;charset=UTF-8");

        PrintWriter out = resp.getWriter();

        out.println("Servlet MySql");

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection= DriverManager.getConnection(DB_URL,USER,PASS);

            stmt=connection.createStatement();
            String sql="select * from users";
            ResultSet resultSet=stmt.executeQuery(sql);



            while (resultSet.next()){
                out.println("---------"+resultSet.getString("user_id")+"   "+resultSet.getString("name"));
            }

//            stmt.close();
//            connection.close();

        } catch (Exception e) {
            e.printStackTrace();
            out.println(e);
        }

    }
}
